package com.example.imserver.service;

import com.example.imserver.entity.FileRecord;
import com.example.imserver.repository.FileRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileService {
    @Value("${file.upload.path}")
    private String uploadPath;
    
    @Value("${file.upload.url}")
    private String fileUrl;
    
    @Autowired
    private FileRecordRepository fileRecordRepository;
    
    public FileRecord saveFile(MultipartFile file, String fileType, Long uploaderId) throws IOException {
        // 创建上传目录
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
        
        // 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName != null && originalFileName.contains(".") 
                ? originalFileName.substring(originalFileName.lastIndexOf(".")) 
                : "";
        String fileName = UUID.randomUUID().toString() + extension;
        String filePath = uploadPath + fileName;
        
        // 保存文件
        File destFile = new File(filePath);
        file.transferTo(destFile);
        
        // 保存文件记录
        FileRecord fileRecord = new FileRecord();
        fileRecord.setFileName(originalFileName);
        fileRecord.setFilePath(fileUrl + fileName);
        fileRecord.setFileType(fileType);
        fileRecord.setFileSize(file.getSize());
        fileRecord.setUploaderId(uploaderId);
        
        return fileRecordRepository.save(fileRecord);
    }
    
    public String getFileUrl(String fileName) {
        return fileUrl + fileName;
    }
}

